package com.tommy.store.http;

import java.io.IOException;

import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClient {

    // 创建HttpClient对象
    // static CloseableHttpClient httpClient = HttpClients.createDefault();
    static String bearerToken = "eyJraWQiOiJLcU8iLCJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIzMmJhZjQzYmRiNmE0Mzg4OGY0NGMwNzU3NzYyNmQzNyIsImF1ZCI6IjNkOWQ3Zjk5ZTU2NjQ3YWI4ZmFkOTVlYTg3MTNhZTI4IiwicyI6ImNhIiwiZCI6IjIzMDgzMDA5MCw3NTc3NTkwOTIiLCJpc3MiOiJhbGlwYW4iLCJleHAiOjE3MjkxMzQxMzcsImlhdCI6MTcyOTEyNjkzNCwianRpIjoiNTg4ZjdlZDY0NTIxNDA2YTkzYjUxZjM0NTU0ZDIyNmQifQ.puNbbaG_C9tqwLQuXW-PXcwAOKuRkBwIrvRwPZgZHqM";

    public static String request(String name, String bodyStr, String bearerToken) {

        String urlBase = "https://openapi.alipan.com";

        String[] _array = ApiConst.urlMap.get(name);
        String url = urlBase + _array[0];
        String method = _array[1];

        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpRequestBase reqInst = new HttpGet(url);

        if (method == "GET") {
            // reqInst = new HttpGet(url);
        } else if (method == "POST") {
            HttpPost tmpPost = new HttpPost(url);
            if (bodyStr != null) {
                StringEntity entity = new StringEntity(bodyStr, ContentType.APPLICATION_JSON);
                tmpPost.setEntity(entity);
            }
            reqInst = tmpPost;
        }

        reqInst.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + bearerToken);

        String result = "";
        try {
            // 发送请求
            CloseableHttpResponse response = httpClient.execute(reqInst);

            // 获取响应的内容
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
            // System.out.println(result);

            // 关闭response
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭httpClient
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }
}
